﻿#region

using Mapster;
using Vin.Extension.Framework.Extension;
using Vin.Extension.Framework.Implement;
using Vin.Extension.Framework.Login.Dto.Entities;
using Vin.Extension.Framework.Login.Dto.List;
using Vin.Extension.Framework.Login.Entities;
using Vin.Extension.Framework.Login.Repository;
using Vin.Extension.Framework.Login.ServiceInterface;
using Vin.Tool.Domain.ExceptionModel;

#endregion

namespace Vin.Extension.Framework.Login.Service;

public class SysAccountBindService :
    VinFrameworkBaseServiceAsync<SysAccountBindDto, SysAccountBindListDto, SysAccountBindRepository, SysAccountBind>,
    ISysAccountBindService
{
    public override async Task<List<SysAccountBindDto>> ListAsync(SysAccountBindListDto dto)
    {
        var list = await _baseRepository.AsQueryable()
            .Where(m => m.AccountId == dto.AccountId && m.IsEnabled == true)
            .ToPageListAsync(dto);
        return list.Adapt<List<SysAccountBindDto>>();
    }

    public async Task<long?> QueryAccountIdByBindAsync(string bindType, string bindValue)
    {
        return await _baseRepository.QueryByBindAsync(bindType, bindValue);
    }

    public async Task BindAsync(long accountId, string bindType, string bindValue, SysAccountBindInfo bindInfo)
    {
        if (!await _baseRepository.CheckCanBindAsync(bindType, bindValue))
        {
            throw new BusinessException($"{bindValue}已被使用");
        }

        var bind = await _baseRepository.QueryByBindTypeAsync(accountId, bindType);
        if (bind != null) throw new BusinessException("请解绑后再重新操作");

        await _baseRepository.SaveOrUpdateAsync(new SysAccountBind()
        {
            AccountId = accountId,
            BindType = bindType,
            BindValue = bindValue,
            BindTime = DateTime.Now,
            BindInfo = bindInfo
        });
    }

    public async Task UnBindAsync(long accountId, string bindType)
    {
        var bind = await _baseRepository.QueryByBindTypeAsync(accountId, bindType);
        if (bind == null) throw new BusinessException("绑定信息不存在");

        bind.IsEnabled = false;
        bind.IsDeleted = true;

        await _baseRepository.SaveOrUpdateAsync(bind);
    }
}